package com.leetroll.media.job;

import com.leetroll.api.service.ItemService;
import com.leetroll.common.entity.Chapter;
import com.leetroll.common.entity.Item;
import com.leetroll.common.enums.EFileType;
import com.leetroll.common.enums.EItemType;
import com.leetroll.common.utils.FileUtils;
import com.leetroll.media.service.UpDownloadService;
import com.leetroll.media.utils.FfmpegUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 概念艺术教程入库 （几年前B站翻译的视频）
 */
@Service
@Slf4j
public class Job_ConceptArt {

    private static final String FILE_PATH = "F:\\_resources\\bilibili\\Blender概念艺术教程";
    private final ExecutorService executor = Executors.newFixedThreadPool(10);
    private final ItemService itemService;
    private final UpDownloadService upDownloadService;

    @Autowired
    public Job_ConceptArt(ItemService itemService, UpDownloadService upDownloadService) {
        this.itemService = itemService;
        this.upDownloadService = upDownloadService;
    }

    public static void main(String[] args) throws Exception {
//        convert2M3u8();
    }

    /**
     * 将视频文件转化为m3u8格式
     */
    public static void convert2M3u8() throws Exception {
        File folder = new File("F:\\_resources\\bilibili\\Blender概念艺术教程\\chapters");
        if (!folder.exists() || !folder.isDirectory() || folder.listFiles() == null) return;
        for (File subFolder : Objects.requireNonNull(folder.listFiles())) {
            if (subFolder.getName().equals("1. 简介篇-从2d到3d的风格化建筑")) continue;
            File[] files = subFolder.listFiles();
            for (File file : Objects.requireNonNull(files)) {
                if (!file.getName().endsWith("mp4")) continue;
                int seq = 1;
                if (file.getName().split("\\.")[0].contains("-")) {
                    seq = Integer.parseInt(file.getName().split("\\.")[0].split("-")[1]);
                }
                String outPath = file.getParent() + "\\" + seq;
                FileUtils.creatFile(outPath);
                FfmpegUtil.videoToM3u8(file.getAbsolutePath(), outPath, String.valueOf(seq));
                log.info("finish > {}", file.getName());
            }
        }
    }

    public void upload() throws Exception {
        File itemFolder = new File(FILE_PATH);
        if (!itemFolder.exists() || !itemFolder.isDirectory()) return;

        //插入item
//        Item item = insertItem(itemFolder.getName());

        //插入章节信息
        File[] subFolders = itemFolder.listFiles();
        if (subFolders == null) return;

        for (File subFolder : subFolders) {
            if (subFolder.getName().equals("chapters")) {
                //上传章节信息
                insertChapters(subFolder, 8335L);
            } else {
                //上传item基础信息
//                insertBasicInfo(subFolder, item.getId());
            }
        }
        log.info("任务完成");
    }

    private void insertBasicInfo(File infoFolder, Long itemId) {
        File[] infos = infoFolder.listFiles();
        if (infos == null) return;
        for (File info : infos) {
            File[] files = info.listFiles();
            if (files == null) continue;
            for (File file : files) {
                if (info.getName().equals(EFileType.ATTACHMENT.getType())) {
                    upDownloadService.upload2AliByType(itemId, file, EFileType.ATTACHMENT);
                } else if (info.getName().equals(EFileType.MAIN.getType())) {
                    upDownloadService.upload2AliByType(itemId, file, EFileType.MAIN);
                } else {
                    upDownloadService.upload2AliByType(itemId, file, EFileType.PREVIEW);
                }
            }
        }
    }

    /**
     * 插入章节信息
     */
    private void insertChapters(File chapterFolder, Long itemId) throws Exception {
        File[] chapters = chapterFolder.listFiles();
        if (chapters == null) return;
        for (File chapter : chapters) {
            if (!chapter.getName().equals("8. 建模篇")) continue;
            uploadChapter(chapter, itemId);
            log.info("chapter[{}] 插入完成", chapter.getName());
        }
    }

    private void uploadChapter(File chapterFolder, Long itemId) throws Exception {
        String title = chapterFolder.getName();
        Chapter chapter = new Chapter();
        chapter.setTitle(title);
        chapter.setDesp("");
        chapter.setItemId(itemId);
        chapter.setChapter(getSeqFromName(title));
//        chapter.insert();

        String mainLink = "";

        File[] files = chapterFolder.listFiles();
        if (files == null) return;

        File mp4 = Arrays.stream(files).filter(file -> file.getName().endsWith("mp4")).collect(Collectors.toList()).get(0);
        String videoTitle = mp4.getName().substring(0, mp4.getName().lastIndexOf("."));
        String format = mp4.getName().substring(mp4.getName().lastIndexOf(".") + 1);
        Long duration = FfmpegUtil.getVideoDuration(mp4.getAbsolutePath());

        for (File file : files) {
            if (file.getName().startsWith("main")) {
                //上传主图到aliyun
//                mainLink = upDownloadService.uploadChapterMain2Ali(itemId, chapter.getId(), file, EFileType.CHAPTER_MAIN);
                log.info("chapter[{}]主图插入完成 > {}", chapter.getId(), mainLink);
            } else if (file.isDirectory()) {
                //上传章节视频到aliyun (m3u8)
                File[] tsFiles = file.listFiles();
                for (File tsFile : Objects.requireNonNull(tsFiles)) {
                    upDownloadService.uploadChapterVideo2Ali(itemId, chapter.getId(), tsFile, EFileType.CHAPTER_VIDEO, file.getName(), videoTitle, format, duration);
                }
                log.info("chapter[{}]视频插入完成", chapter.getId());
            }
        }
        //更新主图信息
        chapter.setMain(mainLink);
//        chapter.updateById();
    }

    private Integer getSeqFromName(String title) {
        String seq = title.split("\\.")[0];
        if (seq.contains("-")) {
            seq = seq.split("-")[0];
        }
        return Integer.valueOf(seq);
    }

    private Item insertItem(String name) {
        log.info("准备插入 item : {}", name);
        //插入item表
        Item item = new Item();
        item.setName(name);
        item.setAlias(name);
        item.setType(EItemType.TUTORIAL.getType());
        item.setAuthor("");
        item.setPrice(0.0);
        item.setCatId(3L);
        item.setStatus("show");
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);

        return item;
    }

}
